package swistak.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import swistak.domain.Product;

public class SimpleProductManager implements ProductManager {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3951433724367969814L;

	private List<Product> products;
	
	protected final Log logger = LogFactory.getLog(getClass());
	
//	@PersistenceContext
	private EntityManager em;
	
	@PersistenceContext
	public void setEntityManager(EntityManager em){
		this.em = em;
	}

	public List<Product> getProducts() {
		return products;
	}
	
	@Transactional
	public List<Product> getProductsDb() {
		List l = em.createQuery("from Product").getResultList();
		return l;
	}

	@Transactional
	public void increasePrice(int percentage) {
		logger.info("increasePrice");
		if (products != null) {
			for (Product product : products) {
				double newPrice = product.getPrice().doubleValue()
						* (100 + percentage) / 100;
				product.setPrice(newPrice);
			}
		}
		addProduct();
	}

	public void setProducts(List<Product> products) {
		this.products = products;
	}
	
	
	public void addProduct(){
		logger.info("add product");
		Product p = new Product();
		p.setDescription("aaa");
		p.setId(2);
		p.setPrice(2.0);
//		em.getTransaction().begin();
		em.persist(p);
		em.flush();
//		em.getTransaction().commit();
	}

}
